//
//  TimeAgo+PPKit.swift
//  PPKit
//
//  Created by xiaopin on 16/8/31.
//  Copyright © 2016年 pinguo. All rights reserved.
//  https://gitee.com/xiaopindev/PPKit
//  https://github.com/xiaopindev
//  https://xiaopin.cnblogs.com

import Foundation

open class TimeAgo: NSObject {

	open class Words: NSObject {
		var yearsAgo = " years ago"
		var monthsAgo = " months ago"
		var weeksAgo = " weeks ago"
		var dayAgo = " day ago"
        var daysAgo = " days ago"
		var hoursAgo = " hours ago"
		var anHourAgo = "An hour ago"
		var minutesAgo = " minutes ago"
		var anMinuteAgo = "A minute ago"
		var secondsAgo = " seconds ago"
		var justNow = "Just now"

		public override init() { super.init() }

		public convenience init(yearsAgo: String, monthsAgo: String, weeksAgo: String, dayAgo: String, daysAgo: String, hoursAgo: String, anHourAgo: String, minutesAgo: String, anMinuteAgo: String, secondsAgo: String, justNow: String) {
			self.init()
			self.yearsAgo = yearsAgo
			self.monthsAgo = monthsAgo
			self.weeksAgo = weeksAgo
			self.dayAgo = dayAgo
            self.daysAgo = daysAgo
			self.hoursAgo = hoursAgo
			self.anHourAgo = anHourAgo
			self.minutesAgo = minutesAgo
			self.anMinuteAgo = anMinuteAgo
			self.secondsAgo = secondsAgo
			self.justNow = justNow
		}
	}

	static let manager = TimeAgo()

	fileprivate override init() {
		super.init()
		let zhhans = Words(yearsAgo: "年前", monthsAgo: "个月前", weeksAgo: "星期前", dayAgo: "1天前", daysAgo: "天前", hoursAgo: "小时前", anHourAgo: "1小时前", minutesAgo: "分钟前", anMinuteAgo: "1分钟前", secondsAgo: "秒钟前", justNow: "刚刚")

		let zhhant = Words(yearsAgo: "年前", monthsAgo: "個月前", weeksAgo: "星期前", dayAgo: "1天前", daysAgo: "天前", hoursAgo: "小時前", anHourAgo: "1小時前", minutesAgo: "分鐘前", anMinuteAgo: "1分鐘前", secondsAgo: "秒鐘前", justNow: "剛剛")
		let en = Words()
		configureForCustomWords["zh-Hans"] = zhhans
		configureForCustomWords["zh-Hant"] = zhhant
		configureForCustomWords["en_US"] = en
	}

	open var configureForCustomWords: [String: Words] = [:]
	open var currentLanguage: String = "en_US"

	var config: Words {
		if let v = configureForCustomWords[currentLanguage] {
			return v
		}
		return Words()
	}
}

extension Date {
	public func timeAgoSinceNow() -> String {
        let calendar = Calendar.current
        let now = Date()
        let unitFlags: Set<Calendar.Component> = [.second, .minute, .hour, .day, .weekOfYear, .month, .year]
        let components = calendar.dateComponents(unitFlags, from: self, to: now)
        let config = TimeAgo.manager.config
        let language = TimeAgo.manager.currentLanguage
        
        let format = DateFormatter()
        var timeAgoStr = config.justNow
        
        /*
         默认：
        if components.year! >= 1 {
            timeAgoStr = format.string(from: self)
        }else if components.month! >= 1 {
            timeAgoStr = "\(components.month!)" + config.monthsAgo
        }else if components.weekOfYear! >= 1 {
            timeAgoStr = "\(components.weekOfYear!)" + config.weeksAgo
        }else if components.day! >= 2 {
            timeAgoStr = "\(components.day!)" + config.daysAgo
        }else if components.day! >= 1 {
            timeAgoStr = config.dayAgo
        }else if components.hour! >= 2 {
            timeAgoStr = "\(components.hour!)" + config.hoursAgo
        }else if components.hour! >= 1 {
            timeAgoStr = config.anHourAgo
        }else if components.minute! >= 2 {
            timeAgoStr = "\(components.minute!)" + config.minutesAgo
        }else if components.minute! >= 1 {
            timeAgoStr = config.anMinuteAgo
        }else if components.second! >= 3 {
            timeAgoStr = "\(components.second!)" + config.secondsAgo
        }
        */
        
        //列表(如文章列表，评论列表，其他列表等)的显示格式：1小时内=刚刚，当天=x小时前，当年=04-19  跨年20-04-29
        if self.year < now.year {
            //跨年
            if language.hasPrefix("zh-"){
                format.dateFormat = "yyyy-MM-dd"
            }else{
                format.dateFormat = "dd MMM yyyy"
            }
            timeAgoStr = format.string(from: self).subString(start: 2)
        }else if components.month! >= 1 || components.weekOfYear! >= 1 || components.day! >= 1 {
            //当年
            if language.hasPrefix("zh-"){
                format.dateFormat = "MM-dd"
            }else{
                format.dateFormat = "dd MMM"
            }
            timeAgoStr = format.string(from: self)
        }else if components.hour! > 1 {
            //当前
            timeAgoStr = "\(components.hour!)" + config.hoursAgo
        }else{
            //1小时内
            timeAgoStr = config.justNow
        }
        
        //PPLog("时间：\(self),TimeAgo:\(timeAgoStr)")
        
        return timeAgoStr
    }
    
    public func timeAgoSinceNow2() -> String {
        
        let calendar = Calendar.current
        let now = Date()
        //let unitFlags: Set<Calendar.Component> = [.second, .minute, .hour, .day, .weekOfYear, .month, .year]
        //let components = calendar.dateComponents(unitFlags, from: self, to: now)
        let config = TimeAgo.manager.config
        let language = TimeAgo.manager.currentLanguage
        
        let format = DateFormatter()
        var timeAgoStr = config.justNow
        
        /*
         群聊显示时间格式：[今天]: HH:mm,  [昨天]: 昨天 HH:mm, [今年内]：MM-dd HH:mm,[去年或更早]：yyyy-MM-dd HH:mm
         */
        if self.year < now.year {
            //满一年：显示yyyy-MM-dd
            if language.hasPrefix("zh-"){
                format.dateFormat = "yyyy-MM-dd HH:mm"
            }else{
                format.dateFormat = "dd MMM yyyy HH:mm"
            }
            timeAgoStr = format.string(from: self)
        }else{
            //不满一年
            if calendar.isDateInToday(self){
                //如果是今天,显示: 今天 HH:mm
                format.dateFormat = "HH:mm"
                timeAgoStr = format.string(from: self)
            }else if calendar.isDateInYesterday(self){
                //如果是昨天,显示: 昨天 HH:mm
                if language.hasPrefix("zh-"){
                    format.dateFormat = "昨天 HH:mm"
                }else{
                    format.dateFormat = "Yesterday HH:mm"
                }
                timeAgoStr = format.string(from: self)
            }else{
                //其他直接显示 MM-dd HH:mm
                if language.hasPrefix("zh-"){
                    format.dateFormat = "MM-dd HH:mm"
                }else{
                    format.dateFormat = "dd MMM HH:mm"
                }
                
                timeAgoStr = format.string(from: self)
            }
        }
        
        //PPLog("时间：\(self),TimeAgo:\(timeAgoStr)")
        
        return timeAgoStr
    }
}

